package net.sf.rose.business.action.define;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.rose.business.bean.action.Action;
import net.sf.rose.business.bean.action.ActionUnitDefineBean;
import net.sf.rose.business.bean.action.ActionUnitSearchBean;
import net.sf.rose.business.bean.action.ActionUnitUpdateBean;
import net.sf.rose.business.bean.action.FieldBean;
import net.sf.rose.business.bean.action.ParamemterBean;
import net.sf.rose.business.service.ActionService;
import net.sf.rose.jdbc.UserBean;
import net.sf.rose.web.OnlineUserListener;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

/**
 * 功能：
 * 
 * @author fengjian
 * @since 2014/01/29
 */
@Controller
@RequestMapping("/define/actionunit")
public class ActionUnitController {

	private static String LIST_PAGE = "define/actionunit/list";
	private static String VIEW_SEARCH_PAGE = "define/actionunit/edit_search_unit";
	private static String VIEW_UPDATE_PAGE = "define/actionunit/edit_update_unit";
	private static String VIEW_DEFINE_PAGE = "define/actionunit/edit_define_unit";
	private static String CONSULT_LIST_PAGE = "define/actionunit/consult";

	/**
	 * 普通查询
	 */
	@RequestMapping("/list.html")
	public ModelAndView list(HttpServletRequest request) {
		Map<String, Action> bean = ActionService.getAllActionUnit();
		String[] sorts = getActionUnitSorts(request);
		ModelAndView mav = new ModelAndView(LIST_PAGE);
		mav.addObject("list", bean);
		mav.addObject("sorts", sorts);
		mav.addObject("sort", "all");
		return mav;
	}

	private String[] getActionUnitSorts(HttpServletRequest request){
		String[] array = null;
		Object obj = request.getSession().getAttribute("action_unit_sorts");
		if (obj == null) {
			Map<String, Action> bean = ActionService.getAllActionUnit();
			Set<String> sorts = new HashSet<String>();
			for (Action a : bean.values()) {
				sorts.add(a.getSort());
			}
			array = new String[sorts.size()];
			Object[] objs = sorts.toArray();
			for (int i = 0; i < sorts.size(); i++) {
				array[i] = objs[i].toString();
			}
			request.getSession().setAttribute("action_unit_sorts", array);
		} else {
			array = (String[]) obj;
		}
		return array;
	}

	/**
	 * 普通查询
	 */
	@RequestMapping("/search.html")
	public ModelAndView search(HttpServletRequest request,String sort,String actionName) {
		Map<String, Action> map = this.getActionUnits(sort, actionName);
		String[] sorts = getActionUnitSorts(request);
		ModelAndView mav = new ModelAndView(LIST_PAGE);
		mav.addObject("list", map);
		mav.addObject("sorts", sorts);
		mav.addObject("sort", sort);
		mav.addObject("actionName", actionName);
		return mav;
	}
	
	/**
	 * 普通查询
	 */
	@RequestMapping("/consult.html")
	public ModelAndView consult(HttpServletRequest request,String sort,String actionName) {
		Map<String, Action> map = this.getActionUnits(sort, actionName);
		String[] sorts = getActionUnitSorts(request);
		ModelAndView mav = new ModelAndView(CONSULT_LIST_PAGE);
		Enumeration<?> en = request.getParameterNames();
		while(en.hasMoreElements()){
			String key = en.nextElement().toString();
			mav.addObject(key,request.getParameter(key));
		}
		mav.addObject("list", map);
		mav.addObject("sorts", sorts);
		mav.addObject("sort", sort);
		mav.addObject("actionName", actionName);
		return mav;
	}

	private Map<String, Action> getActionUnits(String sort,String actionName){
		Map<String, Action> map = null;
		Map<String, Action> bean = ActionService.getAllActionUnit();
		if (sort == null || sort.equals("all")) {
			map = bean;
		} else {
			map = new HashMap<String, Action>();
			for (String key : bean.keySet()) {
				Action a = bean.get(key);
				if (a.getSort().equals(sort)) {
					map.put(key, a);
				}
			}
		}
		if (actionName != null && !actionName.trim().equals("")) {
			String name = actionName.trim();
			Map<String, Action> m = new HashMap<String, Action>();
			for (String key : map.keySet()) {
				Action a = map.get(key);
				if (a.getName().indexOf(name) != -1) {
					m.put(key, a);
				}
			}
			map = m;
		}
		return map;
	}

	/**
	 * 
	 */
	@RequestMapping("/add.html")
	public ModelAndView add(HttpServletRequest request, String action) {
		Action bean = null;
		String view = null;
		if (action.equals("search")) {
			bean = new ActionUnitSearchBean();
			view = VIEW_SEARCH_PAGE;
		} else if (action.equals("update")) {
			bean = new ActionUnitUpdateBean();
			view = VIEW_UPDATE_PAGE;
		} else if (action.equals("define")) {
			bean = new ActionUnitDefineBean();
			view = VIEW_DEFINE_PAGE;
		}
		bean.setActionType(action);
		ModelAndView mav = new ModelAndView(view);
		mav.addObject("bean", bean);
		mav.addObject("actionType", action);
		return mav;
	}

	/**
	 * 
	 */
	@RequestMapping("/get.html")
	public ModelAndView get(HttpServletRequest request, String name) {
		String view = null;
		String actionType = null;
		try {
			name = java.net.URLDecoder.decode(name, "UTF-8");
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		Action bean = ActionService.getAction(name);
		if (bean instanceof ActionUnitSearchBean) {
			view = VIEW_SEARCH_PAGE;
			actionType = "search";
		} else if (bean instanceof ActionUnitUpdateBean) {
			view = VIEW_UPDATE_PAGE;
			actionType = "update";
		} else if (bean instanceof ActionUnitDefineBean) {
			view = VIEW_DEFINE_PAGE;
			actionType = "define";
		}
		ModelAndView mav = new ModelAndView(view);
		mav.addObject("bean", bean);
		mav.addObject("actionType", actionType);
		return mav;
	}

	/**
	 * 
	 */
	@RequestMapping("/delete.html")
	public ModelAndView delete(HttpServletRequest request, HttpServletResponse response, String id) throws Exception {
		id = java.net.URLDecoder.decode(id, "UTF-8");
		ActionService.removeAction(id);
		response.reset();
		response.setContentType("application/json;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		PrintWriter pw = response.getWriter();
		pw.write("{\"msg\":\"删除成功！\"}");
		pw.flush();
		pw.close();
		return null;
	}

	/**
	 * 提交操作
	 */
	@RequestMapping("/save.html")
	public ModelAndView save(HttpServletRequest request) {
		Action action = null;
		String actionType = request.getParameter("actionType");
		if (actionType.equals("search")) {
			ActionUnitSearchBean bean = new ActionUnitSearchBean();
			String str = request.getParameter("cache");
			bean.setCache(str.equals("0") ? false : true);
			str = request.getParameter("sql").trim();
			if (!str.equals("")) {
				bean.setSql(str);
			}
			bean.setParamenters(this.getParamemterBeanList(request));
			action = bean;
		} else if (actionType.equals("update")) {
			ActionUnitUpdateBean bean = new ActionUnitUpdateBean();
			String str = request.getParameter("type").trim();
			if (!str.equals("")) {
				bean.setType(str);
			}
			str = request.getParameter("table.id").trim();
			if (!str.equals("")) {
				bean.setTable(str);
			}
			str = request.getParameter("refresh.name").trim();
			if (!str.equals("")) {
				List<String> list = new ArrayList<String>();
				for (String s : StringUtils.split(str, ',')) {
					list.add(s);
				}
				bean.setRefresh(list);
			}
			str = request.getParameter("rules").trim();
			if (!str.equals("")) {
				bean.setRules(str);
			}
			str = request.getParameter("batchPre").trim();
			if (!str.equals("")) {
				//bean.setBatchPre(str);
			}
			str = request.getParameter("ruleDescription").trim();
			if (!str.equals("")) {
				bean.setRuleDescription(str);
			}
			action = bean;
		} else if (actionType.equals("define")) {
			ActionUnitDefineBean bean = new ActionUnitDefineBean();
			String str = request.getParameter("classname").trim();
			if (!str.equals("")) {
				bean.setClassname(str);
			}
			bean.setFields(getFieldBeanList(request));
			action = bean;
		}
		String str = request.getParameter("name").trim();
		if (!str.equals("")) {
			action.setName(str);
		}
		str = request.getParameter("sort").trim();
		if (!str.equals("")) {
			action.setSort(str);
		}
		str = request.getParameter("description").trim();
		if (!str.equals("")) {
			action.setDescription(str);
		}
		action.setActionType(actionType);

		ActionService.addAction(action);
		ModelAndView mav = new ModelAndView("ajaxDone");
		mav.addObject("statusCode", 200);
		mav.addObject("message", "操作成功！");
		mav.addObject("callbackType", true);
		return mav;
	}

	/**
	 * 提交操作
	 */
	@RequestMapping("/saveAll.html")
	public ModelAndView saveAll(HttpServletRequest request) {
		UserBean user = OnlineUserListener.getOnlineUser(request);
		ActionService.save(user);
		ModelAndView mav = null;
		mav = new ModelAndView("ajaxDone");
		mav.addObject("statusCode", 200);
		mav.addObject("message", "操作成功！");
		mav.addObject("callbackType", true);
		return mav;
	}

	private List<ParamemterBean> getParamemterBeanList(HttpServletRequest request) {
		List<ParamemterBean> list = new ArrayList<ParamemterBean>();
		int i = 0;
		do {
			// 数据库字段名
			String key = request.getParameter("items.fieldName[" + i + "]");
			if (key == null || key.equals("")) {
				break;
			}
			ParamemterBean param = new ParamemterBean();
			param.setFieldName(key);
			// 查询语句字段名
			String searchName = request.getParameter("items.searchName[" + i + "]");
			if (searchName != null && !searchName.equals("")) {
				param.setSearchName(searchName);
			}
			// 替换字段标记
			String replaceName = request.getParameter("items.replaceName[" + i + "]");
			if (replaceName != null && !replaceName.equals("")) {
				param.setReplaceName(replaceName);
			}
			// 参数的数据类型
			String type = request.getParameter("items.type[" + i + "]");
			if (type != null && !type.equals("")) {
				param.setType(type);
			}
			// 参数的数据格式
			String format = request.getParameter("items.format[" + i + "]");
			if (format != null && !format.equals("")) {
				param.setFormat(format);
			}
			// 如果值为空时是否强制添加此条件SQL语句
			String force = request.getParameter("items.force[" + i + "]");
			if (force != null && !force.equals("")) {
				if (force.equals("1")) {
					param.setForce(true);
				}
			}
			// 如果值为空时使用默认值
			String defaultValue = request.getParameter("items.defaultValue[" + i + "]");
			if (defaultValue != null && !defaultValue.equals("")) {
				param.setDefaultValue(defaultValue);
			}
			list.add(param);
			i++;
		} while (i > 0);
		return list;
	}

	private List<FieldBean> getFieldBeanList(HttpServletRequest request) {
		List<FieldBean> list = new ArrayList<FieldBean>();
		int i = 0;
		do {
			// 参数的键值
			String key = request.getParameter("items.key[" + i + "]");
			if (key == null || key.equals("")) {
				break;
			}
			FieldBean param = new FieldBean();
			param.setKey(key);
			// 参数的数据类型
			String type = request.getParameter("items.type[" + i + "]");
			if (type != null && !type.equals("")) {
				param.setType(type);
			}
			// 参数的数据格式
			String format = request.getParameter("items.format[" + i + "]");
			if (format != null && !format.equals("")) {
				param.setFormat(format);
			}
			// 如果值为空时使用默认值
			String value = request.getParameter("items.value[" + i + "]");
			if (value != null && !value.equals("")) {
				param.setValue(value);
			}
			list.add(param);
			i++;
		} while (i > 0);
		return list;
	}

}
